<?php
/*
 * stuResult控制器  学生的成绩分析
 * Tobey
 * */
require_once "baseController.class.php";
class stuResultController extends baseController{

	/*
	获取班级上所有学生得成功和试卷
	ajax   cla_id  np
	*/
	public function getAllGrades(){
		if(IS_AJAX && IS_LOCAL && isset($_POST["cla_id"])){
			$data = $this->classPower();
			if($data["status"] == 1){
				 //学生个数进行分页处理
				if(isset($_POST["np"]) && is_numeric($_POST["np"])){
					$p = $_POST["np"];
				} else{
					$p = 1;
				}
				$sql = D();     //开启连接
                if(IS_PC){
                    $num = 20;
                } else{
                    $num = 10;
                }
                $d["pageInfo"] = $sql->table(array("class_student"=>""))->where(array("class_cla_id"=>$_POST["cla_id"],"is_pass"=>1))->page($p,$num);
            	//获取到所有班级学生的基本信息
                $d["student"] = $sql->table(array("class_student"=>"cs","student"=>"s"))->where(array("cs.class_cla_id"=>$_POST["cla_id"],"cs.is_pass"=>1,"__string__"=>"cs.student_stu_id = s.stu_id"))->field(array("s.stu_number","s.stu_name","s.stu_email","s.stu_id"))->limit(($d["pageInfo"]["np"]-1)*$d["pageInfo"]["num"],$d["pageInfo"]["num"])->select();          
                $d["quiz"] = $sql->table(array("question_set"=>""))->where(array("class_cla_id"=>$_POST["cla_id"],"qus_status"=>array("!=",0)))->field(array("qus_id","qus_name","qus_create_time"))->order("qus_create_time desc")->select();
                if($d["student"]){
            	$stu_num = count($d["student"]);     //班级人数
            } else{
                $stu_num = 0;
            } 
            if($d["quiz"]){
            	$quiz_num = count($d["quiz"]);       //试卷数量
            } else{
                $quiz_num = 0;
            }
            for($i = 0;$i<$stu_num;$i++){
              for($j = 0;$j<$quiz_num;$j++){
               $stu_score = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$d["quiz"][$j]["qus_id"],"stu_id"=>$d["student"][$i]["stu_id"]))->field(array("stu_score"))->find();
               if($stu_score){
                $d["student"][$i]["allResult"][$j]["stu_score"] = $stu_score["stu_score"];
            } else{
                $d["student"][$i]["allResult"][$j]["stu_score"] = "未交";
            }
        }
    }
    $data = $this->message(1,"获取信息成功",$d);
}
$this->ajaxReturn($data);
unset($data);
}
}

     /*
     * 获得试卷的结果统计
     * ajax
     * */
     public function countResult(){
     	if(IS_AJAX && IS_LOCAL && isset($_POST["qus_id"])){
     		$data = $this->quizPower();
     		if($data["status"] == 1){
     		$sql = D();		//开启数据库链接
     		$d["total_score"] = $sql->table(array("question"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("que_score"))->sum();		//获取试卷总分
     		$d["group"] = $this->grouping($d["total_score"]);		//获取分组情况
     		$group_num = count($d["group"]);
     		for($i = 0;$i<$group_num;$i++){					//循环获取每一个分组的人数情况
     			if ($d["group"][$i][0] == $d["group"][$i][1]) {
     				$d["group"][$i]["range"] = $d["group"][$i][0];
     			} else {
     				$d["group"][$i]["range"] = $d["group"][$i][0] . "-" . $d["group"][$i][1];
     			}
     			$d["group"][$i]["num"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"],"stu_score"=>array("between",$d["group"][$i])))->count(); 
     		}
     		$total_num = $sql->table(array("question_set"=>"qs","class"=>"c"))->where(array("qs.qus_id"=>$_POST["qus_id"],"__string__"=>"qs.class_cla_id = c.cla_id"))->field(array("cla_stu_num"))->find();				//获取班级的学生总数
     		$d["stu_num"] = $total_num["cla_stu_num"];			
     		$d["submitNum"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->count();			//获取已提交的人数
     		$d["max"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("stu_score"))->max();         //获得最高分
            $d["min"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("stu_score"))->min();        //获得最低分
            $d["avg"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("stu_score"))->avg();         //获得平均分
            $d["passNum"] = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"],"stu_score"=>array(">=",ceil($d["total_score"] * 0.6))))->count();           //获得合格的人数
            $d["datetime"] = date("Y-m-d H:m:i",time());;        //获得当前时间
            //获取试卷的题目情况
            $d["questions"] = $sql->table(array("question"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("que_id","que_type","que_content","que_num","que_item1","que_item2","que_item3","que_item4","que_item5",
            	"que_item6","que_item7","que_item8","que_answer","que_score"))->order("que_num")->select();
            // var_dump( $d["questions"])
            $que_num = count($d["questions"]);
            for($i = 0;$i<$que_num;$i++){
            	for($j = 0;$j<8;$j++){
                    if($d["questions"][$i]["que_item".($j+1)] != null){          //清除null的选项
                    	$d["questions"][$i]["que_item"][$j] = array("content" => $d["questions"][$i]["que_item".($j+1)]);
                    }
                    unset($d["questions"][$i]["que_item".($j+1)]);
                }
            }
            // //计算每个题目的答题情况
            for ($i = 0; $i < $que_num; $i++) {
                $total_answer = $sql->table(array("student_question"=>""))->where(array("que_id"=>$d["questions"][$i]["que_id"]))->count();
                if($total_answer){
                $d["questions"][$i]["accuracy"] = (round($sql->table(array("student_question"=>""))->where(array("que_id"=>$d["questions"][$i]["que_id"],"is_correct"=>1))->count() / $total_answer,4)*100)."%"; //计算正确率
            } else{
             $d["questions"][$i]["accuracy"] = "0%";
         }
         if($d["questions"][$i]["que_type"] < 3){
                for ($j = 0; $j < count($d["questions"][$i]["que_item"]); $j++) {     //计算题目的选择人数
                    $d["questions"][$i]["que_item"][$j]["num"] = $sql->table(array("student_question"=>""))->where(array("que_id"=>$d["questions"][$i]["que_id"],"stu_answer"=>array("like","%".$j."%")))->count();           //选择人数
                    $item_select = $sql->table(array("student_question"=>""))->where(array("que_id"=>$d["questions"][$i]["que_id"]))->count();
                    if($item_select){
                        $d["questions"][$i]["que_item"][$j]["per"] = (round($d["questions"][$i]["que_item"][$j]["num"] / $item_select,4)*100)."%";			//正确百分比
                    } else{
                        $d["questions"][$i]["que_item"][$j]["per"] = "0%";
                    }
                }
            }
        }
        $data = $this->message(1,"获取信息成功!",$d);
    }
    $this->ajaxReturn($data);
    unset($data);
}
}

    /*
     * 分组处理
     * 代码中调用
     * */
    private function grouping($total_score){
        if($total_score+1<=6){              //总分+1小于等于6的分法
        	$divide = $total_score + 1;
        	for($i = 0;$i<$divide;$i++){
        		$group[$i] = array($i,$i);
        	}
        } else {
        	$divide = 6;
        	$chaju = ($total_score + 1) % 6 / floor(($total_score + 1) / $divide);
        	if ($chaju == 0) {
        		$divide = 6;
        	} else {
                for ($i = 7; $i < 10; $i++) {           //最多分10组  最少分1组
                	$temp_chaju = (($total_score + 1) % $i) / (floor(($total_score + 1) / $i));
                	if ($temp_chaju == 1 || $temp_chaju == 0) {
                		$divide = $i;
                        break;          //特殊情况退出循环
                    }
                    else if (abs(1-$temp_chaju) < abs(1-$chaju)) {
                    	$chaju = $temp_chaju;
                    	$divide = $i;
                    }
                }
            }
            $start = 0;     //组织分组
            $end = floor(($total_score + 1) / $divide) - 1;
            for ($i = 0; $i < $divide; $i++) {
            	$group[$i] = array($start,$end);
            	$start = $end + 1;
                if ($i < $divide - 1) {            //正常处理
                	$end = $start + floor(($total_score + 1) / $divide) - 1;
                } else {                //增组处理
                	$end = $start + ($total_score + 1) % $divide - 1;
                }
            }
            if (($total_score + 1) % $divide != 0) {       //增组处理
            	$group[$i] = array($start,$end);
            }
        }
        return $group;
    }
    /*
    获取某些同学的答题成绩情况  search
    ajax  本地  cla_id   key关键字=学生学号|名称   np当前页面
    */
    public function searchStuGrade(){
        if(IS_AJAX && IS_LOCAL && isset($_POST["cla_id"])){
            $data = $this->classPower();
            if($data["status"] == 1){
                $sql = D();         //开启数据库连接
                // 分页信息
                if(isset($_POST["np"]) && is_numeric($_POST["np"])){
                    $p = $_POST["np"];
                } else{
                    $p = 1;
                }
                if(IS_PC){
                    $num = 20;
                } else{
                    $num = 10;
                }
                $d["pageInfo"] = $sql->table(array("class_student"=>"cs","student"=>"s"))->where(array("cs.class_cla_id"=>$_POST["cla_id"],"cs.is_pass"=>1,"s.stu_number|s.stu_name"=>array("like","%".$_POST["key"]."%"),"__string__"=>"cs.student_stu_id = s.stu_id"))->page($p,$num);
                // 获取班级上全部学生的基本信息
                $d["student"] = $sql->table(array("class_student"=>"cs","student"=>"s"))->where(array("cs.class_cla_id"=>$_POST["cla_id"],"cs.is_pass"=>1,"s.stu_number|s.stu_name"=>array("like","%".$_POST["key"]."%"),"__string__"=>"cs.student_stu_id = s.stu_id"))->field(array("s.stu_id","s.stu_number","s.stu_name","s.stu_email","s.sex"))->limit(($d["pageInfo"]["np"]-1)*$d["pageInfo"]["num"],$d["pageInfo"]["num"])->select();
                if(!$d["student"]){
                    $d["student"] = array();
                }
                $student_len = count($d["student"]);
                // 获取班级上全部试卷的基本信息
                $d["quiz"] = $sql->table(array("question_set"=>""))->where(array("class_cla_id"=>$_POST["cla_id"],"qus_status"=>array("!=",0)))->field(array("qus_id","qus_name","qus_status","qus_create_time"))->order("qus_id desc")->select();
                if(!$d["quiz"]){
                    $d["quiz"] = array();
                }
                $quiz_len = count($d["quiz"]);
                //获取每个学生每张试卷的成绩情况
                $table = array("student_result"=>"");
                for($i = 0;$i < $student_len;$i++){
                    for($j = 0;$j < $quiz_len;$j++){
                        $result = $sql->table($table)->where(array("qus_id"=>$d["quiz"][$j]["qus_id"],"stu_id"=>$d["student"][$i]["stu_id"]))->field(array("stu_score"))->find();
                        if(!$result){
                            $result["stu_score"] = "未交";
                        }
                        $d["student"][$i]["allResult"][$j]["stu_score"] = $result["stu_score"];
                    }
                }
                $data = $this->message(1,"获取信息成功",$d);
                unset($student_len,$quiz_len,$sql,$table,$d);
            }
            $this->ajaxReturn($data);
            unset($data);
        }
    }

    /*
    重新阅卷  
    ajax  本地  qus_id
     */
    public function reappraise(){
        if(IS_AJAX && IS_LOCAL && isset($_POST["qus_id"])){
            $data = $this->quizPower();
            if($data["status"] == 1){
                $sql = D();
                $student = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("stu_id"))->select();
                $ques = $sql->table(array("question"=>""))->where(array("qus_id"=>$_POST["qus_id"],"que_type"=>array("in",array(0,1,2,3))))->field(array("que_id","que_answer"))->select();
                $student_len = count($student);
                $ques_len = count($ques);
                $success = 0;
                $where["qus_id"] = $_POST["qus_id"];
                for($i = 0;$i < $student_len;$i++){
                    for($j = 0;$j<$ques_len;$j++){
                        $stu_answer = $sql->table(array("student_question"=>""))->where(array("que_id"=>$ques[$j]["que_id"],"stu_id"=>$student[$i]["stu_id"]))->field(array("stu_answer","is_correct"))->find();
                        if($stu_answer){
                            if($stu_answer["stu_answer"] == $ques[$j]["que_answer"] && $stu_answer["is_correct"] == 0){
                                $update["is_correct"] = 1;
                            } else if($stu_answer["stu_answer"] != $ques[$j]["que_answer"] && $stu_answer["is_correct"] == 1){
                                $update["is_correct"] = 0;
                            }
                            if(isset($update)){
                                if($sql->table(array("student_question"=>""))->where(array("que_id"=>$ques[$j]["que_id"],"stu_id"=>$student[$i]["stu_id"]))->update($update)){
                                    $success++;
                                }
                            }
                            unset($update);
                        }
                    }
                    $score = $sql->table(array("question"=>"que","student_question"=>"sq"))->where(array("que.qus_id"=>$_POST["qus_id"],"sq.is_correct"=>1,"sq.stu_id"=>$student[$i]["stu_id"],"__string__"=>"que.que_id = sq.que_id"))->field(array("que_score"))->sum();
                    if(is_numeric($score)){
                        $update["stu_score"] = $score;
                    } else{
                        $update["stu_score"] = 0;
                    }
                    $where["stu_id"] = $student[$i]["stu_id"];
                    $sql->table(array("student_result"=>""))->where($where)->update($update);
                }
                if($success){
                    $data = $this->message(1,"重新阅卷成功!","");
                } else{
                    $data = $this->message(0,"无需重新阅卷!","");
                }
                unset($sql,$student,$ques,$student_len,$ques_len,$success,$where);
            }
            $this->ajaxReturn($data);
            unset($data);
        }
    }

    /*
    获取登录学生的某个班级的试卷成绩情况
    ajax  本地  cla_id
    */
    public function stuQuizGrade(){
        if(IS_AJAX && IS_LOCAL && isset($_POST["cla_id"])){
            $data = $this->stuClassPower();
            if($data["status"] == 1){
                session_start();
                $stu_id = $_SESSION["id"];
                session_write_close();
                $sql = D();  //开启数据库
                $d["quiz"] = $sql->table(array("question_set"=>""))->where(array("class_cla_id"=>$_POST["cla_id"],"qus_status"=>2))->field(array("qus_id","qus_name","qus_create_time"))->select();
                if($d["quiz"]){
                    $quiz_num = count($d["quiz"]);
                    for($i = 0;$i < $quiz_num;$i++){
                        $stu_score = $sql->table(array("student_result"=>""))->where(array("qus_id"=>$d["quiz"][$i]["qus_id"],"stu_id"=>$stu_id))->field(array("stu_score"))->find();
                        if($stu_score){
                            $d["quiz"][$i]["stu_score"] = $stu_score["stu_score"];
                        } else{
                            $d["quiz"][$i]["stu_score"] = "未交";
                        }
                    }
                } else{
                    $d["quiz"] = array();
                }
                $data = $this->message(1,"获取信息成功!",$d);
                unset($d,$sql,$stu_id);
            }
            $this->ajaxReturn($data);
            unset($data);
        }
    }

    /*
    学生提交试卷
    ajax  本地  qus_id试卷id
    */
    public function commitQus(){
        if(IS_AJAX && IS_LOCAL && isset($_POST["qus_id"])){
            $data = $this->stuQuizPower();
            if($data["status"] == 1){
                $sql = D();
                $qus = $sql->table(array("question_set"=>""))->where(array("qus_id"=>$_POST["qus_id"]))->field(array("qus_status"))->find();
                if($qus && $qus["qus_status"] == 1){
                    //获取回答正确的答案
                    session_start();
                    $stu_id = $_SESSION["id"];
                    session_write_close();
                    $score = $sql->table(array("question"=>"que","student_question"=>"sq"))->where(array("que.qus_id"=>$_POST["qus_id"],"sq.is_correct"=>1,"sq.stu_id"=>$stu_id,"que.que_type"=>array("in",array(0,1,2,3)),"__string__"=>"que.que_id = sq.que_id"))->field(array("que_score"))->sum();
                    if(is_numeric($score)){
                        $add["stu_score"] = $score;
                    } else{
                        $add["stu_score"] = 0;
                    }
                    $add["qus_id"] = $_POST["qus_id"];
                    $add["stu_id"] = $stu_id+0;
                    if($sql->table(array("student_result"=>""))->where(array("qus_id"=>$_POST["qus_id"],"stu_id"=>$stu_id))->count() == 0){
                        if(is_numeric($sql->table(array("student_result"=>""))->add($add))){
                            $data = $this->message(1,"提交试卷成功!","");
                        } else{
                            $data = $this->message(0,"提交试卷失败!","");
                        }
                    } else{
                        $data = $this->message(0,"已经提交过试卷了,请勿重复提交!","");
                    }
                    unset($stu_id,$score,$add);
                } else{
                    $data = $this->message(0,"试卷已经结束,无法提交!","");
                }
                unset($sql,$qus);
            }
            $this->ajaxReturn($data);
            unset($data);
        }
    }

	/**
  	 * 析构函数不用写任何内容也是可以的
  	 */
	public function __destruct(){}
}
